package cn.afterturn.easypdf.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.util.Store;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class PdfSignatureUtil {


    /**
     * 获取pdf签名数据
     * @param pdDocument
     * @return
     */
    public static List<String> getSign(PDDocument pdDocument) {
        List<String> signList = new ArrayList<>();
        try {
            List<PDSignature> list = pdDocument.getSignatureDictionaries();
            if (list != null && list.size() > 0) {
                PDSignature signature = list.get(0);
                byte[] signatureBytes = signature.getContents();

                // 解析CMS签名数据
                CMSSignedData signedData = new CMSSignedData(signatureBytes);
                Store certStore = signedData.getCertificates();
                // 获取签名者信息
                SignerInformationStore signers = signedData.getSignerInfos();
                for (SignerInformation signerInfo : signers) {
                    // 获取证书 无数版本是真难啊
                    Collection<X509CertificateHolder> certificates = certStore.getMatches(signerInfo.getSID());
                    X509CertificateHolder cert = certificates.iterator().next();
                    X500Name subjectDN = cert.getSubject();
                    signList.add(subjectDN.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return signList;
    }
}
